package com.magupe.im.web.handler.websocket;

import com.magupe.im.web.db.service.DataService;
import com.magupe.im.web.protocol.request.GroupMessageRequest;
import com.magupe.im.web.utils.UUIDUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class WebsocketGroupMessageHandler extends SimpleChannelInboundHandler<GroupMessageRequest> {

    protected Logger logger = LoggerFactory.getLogger(WebsocketGroupMessageHandler.class);

    private DataService dataService;

    public WebsocketGroupMessageHandler(DataService dataService){
        this.dataService = dataService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupMessageRequest request) throws Exception {
        // 0.设置id
        request.setId(UUIDUtil.getUuid());

        logger.debug("websocket signal communication. group message: {}", request.toString());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务时间： " + new Date().getTime()));
        ReferenceCountUtil.release(request);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("websocket signal communication. group error: {}", cause);
        ctx.close();
    }
}
